package edu.ynu.se.xiecheng.achitectureclass.common.utils;

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class TokenUtil1 {

    // 配置常量
    private static final String TOKEN_URL = "https://fbox360.com/idserver/core/connect/token";
    private static final String CLIENT_ID = "68db2e8bda8d47b5b5db7eaf71c7dcdd";
    private static final String CLIENT_SECRET = "76dc724c95004acab25482d344dab407";
    private static final String SCOPE = "fbox";
    private static final String GRANT_TYPE = "client_credentials";

    // 可选：缓存 Token 和过期时间
    private static String cachedToken = null;
    private static long tokenExpiryTime = 3600;

    /**
     * 获取 Access Token
     * @return Access Token 字符串
     */
    public static String fetchToken() {
        // 如果缓存的 Token 未过期，直接返回缓存的 Token
        if (cachedToken != null && System.currentTimeMillis() < tokenExpiryTime) {
            return cachedToken;
        }

        // 请求头配置
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 请求体配置
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("scope", SCOPE);
        requestBody.put("client_id", CLIENT_ID);
        requestBody.put("client_secret", CLIENT_SECRET);
        requestBody.put("grant_type", GRANT_TYPE);

        // 将请求体转换为表单格式
        StringBuilder formBody = new StringBuilder();
        requestBody.forEach((key, value) -> formBody.append(key).append("=").append(value).append("&"));
        formBody.deleteCharAt(formBody.length() - 1); // 移除最后一个 "&"

        HttpEntity<String> requestEntity = new HttpEntity<>(formBody.toString(), headers);

        // 发送 POST 请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Map> response = restTemplate.exchange(TOKEN_URL, HttpMethod.POST, requestEntity, Map.class);

        // 解析响应
        if (response.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null) {
                String token = (String) responseBody.get("access_token");
                int expiresIn = (int) responseBody.get("expires_in"); // 获取 Token 有效期（秒）

                // 缓存 Token 和过期时间
                cachedToken = token;
                tokenExpiryTime = System.currentTimeMillis() + (expiresIn * 1000L);

                return token;
            } else {
                throw new RuntimeException("Invalid token response format");
            }
        } else {
            throw new RuntimeException("Failed to fetch token. Status code: " + response.getStatusCode());
        }
    }
}
